package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.QueryParam;
import com.itheima.pojo.Student;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult page(QueryParam queryParam) {
        //1.处理page和pageSize
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());
        //2.调用mapper方法执行查询
        List<Student> clazzList =  studentMapper.list(queryParam);
        //将得到的List转换成Page集合
        Page<Student> p = (Page<Student>) clazzList;
        //返回封装的页面信息
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public void addStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.add(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void updateViolationById(Integer id, Integer score) {
        //违纪处理一次，需要将违纪次数+1，违纪扣分+前端输入的分数。
        //我的思路，先获取数据库中的违纪次数和违纪扣分
        Student student = getById(id);
        //在service中进行数据处理
        Integer newCount = student.getViolationCount() + 1;
        Integer newScore = student.getViolationScore() + score;
        //再将处理后的数据更新到数据库
        studentMapper.updateById(id,newCount,newScore);
    }
}
